package com.fmy.test.config.dynamic.interceptor;


import com.fmy.test.config.dynamic.algorithm.DBAlgorithm;
import com.fmy.test.config.dynamic.enums.DBType;
import com.fmy.test.config.dynamic.holder.DynamicContextHolder;
import com.fmy.test.config.dynamic.holder.DynamicHolderModel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

@Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MasterSlaveAutoRoutingPlugin implements Interceptor {

    private final static Log log = LogFactory.getLog(MasterSlaveAutoRoutingPlugin.class);

    private DBAlgorithm algorithm;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        try {
            DBType dbType = SqlCommandType.SELECT == ms.getSqlCommandType() ? DBType.READ_DB : DBType.WRITE_DB;
            String dbName = algorithm.getDB(dbType);
            if (log.isInfoEnabled()) log.info("当前使用数据源：" + dbName);
            DynamicContextHolder.set(new DynamicHolderModel(dbName, dbType));
            return invocation.proceed();
        } finally {
            DynamicContextHolder.remove();
        }
    }

    @Override
    public Object plugin(Object target) {
        return target instanceof Executor ? Plugin.wrap(target, this) : target;
    }

    @Override
    public void setProperties(Properties properties) {
    }

    public void setAlgorithm(DBAlgorithm algorithm) {
        this.algorithm = algorithm;
    }
}
